﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace FySystem.Configuration
{
    public class UserStorage
    {
        /// <summary>
        /// 读取用户记录文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">文件名，比如rec.txt，只需要文件名，不要传路径，如果文件不存在
        /// ，返回null，如果已存在，则读取。</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static T ReadStorageFile<T>(string fileName="rec")
        {
            T res = default(T);
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + fileName;
                if (File.Exists(path) == true)
                {
                    using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read))
                    {
                        using (StreamReader sr = new StreamReader(fs))
                        {
                            string jsn = sr.ReadToEnd();
                            if (!string.IsNullOrWhiteSpace(jsn))
                            {
                                res = JsonSerializer.Deserialize<T>(jsn);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }

        /// <summary>
        /// 写入用户记录文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        public static void WriteStorageFile<T>(T model, string fileName="rec")
        {
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + fileName;
                if (File.Exists(path))
                    File.Delete(path);

                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        string jsn = string.Empty;
                        if (model != null)
                            jsn = JsonSerializer.Serialize(model);
                        sw.WriteLine(jsn);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
